import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

// create an axios instance
const service = axios.create({
  // 基准路径
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // 超时
})

// 请求拦截器
service.interceptors.request.use((config) => {
  // console.log(1000, config)
  // 主动介入
  if (store.getters.token) {
    const timeout = 1000 * 60 * 60 * 2
    const loginTime = localStorage.getItem('loginTime')
    const now = Date.now()
    if (now - loginTime > timeout) {
      // 超时
      store.dispatch('user/logout')
      return Promise.reject(new Error('token超时(主动介入)'))
    }
    config.headers.Authorization = store.getters.token
  }
  return config
})

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    // console.log(1777, res);
    const { code, msg } = res.data
    if (code == '200') {
      // 完全成功
      return res.data
    } else {
      // 数据层面失败
      Message.error(msg)
      // console.log(message)
      return Promise.reject(new Error(msg))
    }
  },
  (err) => {
    // console.log('网络层面失败')
    console.dir(err)
    // 被动介入
    if (err.response && err.response.data.code === 10002) {
      store.dispatch('user/logout')
    }
    Message.error(err.message)
    return Promise.reject(new Error(err.message))
  }
)

export default service
